package com.blog.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CookieUtil {
	
	/*
	 		X: domain=".lmyau.com"
	 	
	 	a: A.lmyau.com			cookie: domain=A.lmyau.com;path="/"
	 	b: B.lmyau.com			cookie: domain=B.lmyau.com;path="/"
	 	c: A.lmyau.com/test/cc	cookie: domain=A.lmyau.com;path="test/cc"
	 	d: A.lmyau.com/test/dd	cookie: domain=A.lmyau.com;path="test/dd"
	 	e: A.lmyau.com/test		cookie: domain=A.lmyau.com;path="/test"
	 	
	 	当domain设置为 X 时,
	 			a   b 是互不共享cookie的, 
	 			c   d 也是互不共享cookie的,
	 			c   d 都可以访问a的cookie, 也都可以访问e的cookie.		
	 	
	 */
		
	//private static String DOMAIN_NAME = ".lmyau.com";
	private static String DOMAIN_NAME = "localhost";
	private static String COOKIE_NAME = "blog_login_token";
	
	private static Logger log = LoggerFactory.getLogger(CookieUtil.class);
	
	//读取cookie
	public static String readLoginToken(HttpServletRequest request){
		
		Cookie[] cks = request.getCookies();
		
		if(cks != null){
			for(Cookie ck : cks){
				
				log.info("cookie name:{},cookie value: {}",ck.getName(),ck.getValue());
				
				if(StringUtils.equals(ck.getName(), COOKIE_NAME)){
				
					log.info("return cookie name: {},cookie value: {}",ck.getName(),ck.getValue());
					return ck.getValue();
				}
				
			}
		}
		return null;
		
	}
	
	//写cookie
	public static void writeLoginToken(HttpServletResponse response, String token){
		
		
		Cookie cookie = new Cookie(COOKIE_NAME, token);
		
		//设置cookie所属域
		cookie.setDomain(DOMAIN_NAME);
		
		//代表设置在根目录
		cookie.setPath("/");
		
		//设置过期时间 ,单位为秒 , 
		//若设为0,则代表删除cookie
		//若设为-1,则代表永不过期
		//若不设置,cookie不会写入硬盘,只写在内存,只在当前页面有效.
		cookie.setMaxAge(60 * 60 * 24);
		
		log.info("write cookie, cookie name is {}, cookie value is {}",cookie.getName(),cookie.getValue()	);
		
		response.addCookie(cookie);
		 
	}
	
	
	//删除cookie
	public static void delLoginToken(HttpServletRequest request,HttpServletResponse response){
		
		Cookie[] cks = request.getCookies();
		
		if(cks != null){
			
			for(Cookie ck : cks){
				
				if(StringUtils.equals(COOKIE_NAME, ck.getName())){
				
					ck.setDomain(DOMAIN_NAME);
					ck.setPath("/");
					ck.setMaxAge(0);
					log.info("delete cookie , cookie name is {}, cookie value is {}",ck.getName(),ck.getValue());
					response.addCookie(ck);
					return;
				}
			}
		}
	}
	
}
